/**
 * @file 密码管理器 IPC 处理器
 * @description 处理渲染进程与主进程之间的密码管理器相关通信
 * @author AI Assistant
 * @version 1.0.0
 * @since 2025-10-22
 */

import { ipcMain } from 'electron'
import { databaseManager } from '#/database'
import type {
  CreateUserCredentialInput,
  QueryUserCredentialParams,
  UpdateUserCredentialInput
} from '#/database/models/user-credential.model'
import { calculatePasswordStrength, generateSecurePassword } from '#/utils/encryption'
import { createRuntimeState } from 'global-state'
import { PASSWORD_MANAGER_CHANNELS } from '~shared/ipc-topic'

const passStore = createRuntimeState('passStore', {
  credentialId: '',
  domain: '',
  username: '',
  password: '',
  site_name: '',
  favicon_url: '',
  url: '',
  windowId: 0
} as F2.user.WebCredential)

/**
 * 注册密码管理器 IPC 处理器
 */
export function registerPasswordManagerHandlers(): void {
  const passwordManagerService = databaseManager.getPasswordManagerService()
  // 添加凭据
  ipcMain.handle(
    PASSWORD_MANAGER_CHANNELS.ADD_CREDENTIAL,
    async (_, input: CreateUserCredentialInput) => {
      try {
        return await passwordManagerService.addCredential(input)
      } catch (error) {
        console.error('添加凭据失败:', error)
        return {
          success: false,
          error: error instanceof Error ? error.message : '添加凭据失败'
        }
      }
    }
  )

  // 更新凭据
  ipcMain.handle(
    PASSWORD_MANAGER_CHANNELS.UPDATE_CREDENTIAL,
    async (_, input: UpdateUserCredentialInput) => {
      try {
        return await passwordManagerService.updateCredential(input)
      } catch (error) {
        console.error('更新凭据失败:', error)
        return {
          success: false,
          error: error instanceof Error ? error.message : '更新凭据失败'
        }
      }
    }
  )

  // 删除凭据
  ipcMain.handle(PASSWORD_MANAGER_CHANNELS.DELETE_CREDENTIAL, async (_, id: string) => {
    try {
      return await passwordManagerService.deleteCredential(id)
    } catch (error) {
      console.error('删除凭据失败:', error)
      return {
        success: false,
        error: error instanceof Error ? error.message : '删除凭据失败'
      }
    }
  })

  // 查询凭据（加密数据）
  ipcMain.handle(
    PASSWORD_MANAGER_CHANNELS.QUERY_CREDENTIALS,
    async (_, params: QueryUserCredentialParams) => {
      try {
        return await passwordManagerService.queryCredentials(params)
      } catch (error) {
        console.error('查询凭据失败:', error)
        return {
          success: false,
          error: error instanceof Error ? error.message : '查询凭据失败'
        }
      }
    }
  )

  // 获取解密凭据
  ipcMain.handle(
    PASSWORD_MANAGER_CHANNELS.GET_DECRYPTED_CREDENTIALS,
    async (_, params: QueryUserCredentialParams) => {
      try {
        return await passwordManagerService.getDecryptedCredentials(params)
      } catch (error) {
        console.error('获取解密凭据失败:', error)
        return {
          success: false,
          error: error instanceof Error ? error.message : '获取解密凭据失败'
        }
      }
    }
  )

  // 更新最后使用时间
  ipcMain.handle(PASSWORD_MANAGER_CHANNELS.UPDATE_LAST_USED, async (_, id: string) => {
    try {
      return await passwordManagerService.updateLastUsed(id)
    } catch (error) {
      console.error('更新最后使用时间失败:', error)
      return {
        success: false,
        error: error instanceof Error ? error.message : '更新失败'
      }
    }
  })

  // 获取设置
  ipcMain.handle(PASSWORD_MANAGER_CHANNELS.GET_SETTINGS, async () => {
    try {
      return await passwordManagerService.getSettings()
    } catch (error) {
      console.error('获取设置失败:', error)
      return {
        success: false,
        error: error instanceof Error ? error.message : '获取设置失败'
      }
    }
  })

  // 生成安全密码
  ipcMain.handle(PASSWORD_MANAGER_CHANNELS.GENERATE_PASSWORD, async (_, length = 16) => {
    try {
      const password = generateSecurePassword(length)
      return { success: true, data: password }
    } catch (error) {
      console.error('生成密码失败:', error)
      return {
        success: false,
        error: error instanceof Error ? error.message : '生成密码失败'
      }
    }
  })

  // 检查密码强度
  ipcMain.handle(PASSWORD_MANAGER_CHANNELS.CHECK_PASSWORD_STRENGTH, async (_, password: string) => {
    try {
      const strength = calculatePasswordStrength(password)
      return { success: true, data: strength }
    } catch (error) {
      console.error('检查密码强度失败:', error)
      return {
        success: false,
        error: error instanceof Error ? error.message : '检查密码强度失败'
      }
    }
  })

  // 显示保存密码提示弹窗
  ipcMain.handle(
    PASSWORD_MANAGER_CHANNELS.SHOW_SAVE_PROMPT,
    async (event, data: F2.user.WebCredential) => {
      console.log('显示保存密码提示:', event)
      try {
        passStore.set({ ...data, windowId: event.sender.id })
        return { success: true }
      } catch (error) {
        console.error('显示保存密码提示失败:', error)
        return {
          success: false,
          error: error instanceof Error ? error.message : '显示提示失败'
        }
      }
    }
  )

  // 同步到云端
  ipcMain.handle(PASSWORD_MANAGER_CHANNELS.SYNC_TO_CLOUD, async () => {
    try {
      return await passwordManagerService.syncToCloud()
    } catch (error) {
      console.error('同步到云端失败:', error)
      return {
        success: false,
        error: error instanceof Error ? error.message : '同步到云端失败'
      }
    }
  })

  // 从云端同步
  ipcMain.handle(
    PASSWORD_MANAGER_CHANNELS.SYNC_FROM_CLOUD,
    async (_, cloudCredentials: F2.user.UserCredential[]) => {
      try {
        return await passwordManagerService.syncFromCloud(cloudCredentials)
      } catch (error) {
        console.error('从云端同步失败:', error)
        return {
          success: false,
          error: error instanceof Error ? error.message : '从云端同步失败'
        }
      }
    }
  )

  console.log('✅ 密码管理器 IPC 处理器已注册')
}
